package com.innovation.ic.im.end.web.controller.im_erp9;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.innovation.ic.b1b.framework.util.StringUtils;
import com.innovation.ic.im.end.base.model.im_erp9.*;
import com.innovation.ic.im.end.base.pojo.ApiResult;
import com.innovation.ic.im.end.base.pojo.ServiceResult;
import com.innovation.ic.im.end.base.pojo.constant.Constants;
import com.innovation.ic.im.end.base.pojo.constant.RabbitMqExchangeMap;
import com.innovation.ic.im.end.base.pojo.constant.RedisStorage;
import com.innovation.ic.im.end.base.pojo.im_erp9.*;
import com.innovation.ic.im.end.base.thread.web.SendRabbitMqMessageThread;
import com.innovation.ic.im.end.base.value.config.RabbitMqParamConfig;
import com.innovation.ic.im.end.base.vo.im_erp9.AccountVo;
import com.innovation.ic.im.end.base.vo.im_erp9.BlurSearchScAccountVo;
import com.innovation.ic.im.end.web.controller.AbstractController;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 账号API
 */
@Api(value = "账号API", tags = "AccountController")
@RestController
@RequestMapping("/api/v1/account")
@DefaultProperties(defaultFallback = "defaultFallback")
public class AccountController extends AbstractController {
    private static final Logger log = LoggerFactory.getLogger(AccountController.class);

    @Resource
    private RabbitMqParamConfig rabbitMqParamConfig;

    /**
     * 根据adminsId获取账号的详细信息
     *
     * @return
     */
    @HystrixCommand
    @ApiOperation(value = "根据adminsId获取账号的详细信息")
    @ApiImplicitParam(name = "adminsId", value = "账号", required = true, dataType = "String")
    @RequestMapping(value = "/detailByAdminsId/{adminsId}", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult> detailByAdminsId(@PathVariable("adminsId") String adminsId, HttpServletRequest request, HttpServletResponse response) {
        if (!StringUtils.validateParameter(adminsId)) {
            String message = "调用接口【/api/v1/account/detailByAdminsId/{adminsId}时，参数adminsId不能为空";
            log.warn(message);
            ApiResult<Account> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        //ServiceResult<Account> serviceResult = accountService.findById(adminsId);
        //从Redis获取account数据
        String accountDTO = (String) redisManager.get(RedisStorage.ACCOUNT_BY_ADMINS_ID_PREFIX + adminsId);
        ApiResult<Account> apiResult = new ApiResult<>();
        apiResult.setSuccess(Boolean.TRUE);
        apiResult.setCode(HttpStatus.OK.value());
        //解析数据
        JSONObject json = (JSONObject) JSONObject.parse(accountDTO);
        if (json != null && !json.isEmpty()) {
            apiResult.setResult(JSONObject.parseObject(json.toJSONString(), Account.class));
        }
        apiResult.setMessage(ServiceResult.SELECT_SUCCESS);
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 根据account获取账号的详细信息
     *
     * @return
     */
    @HystrixCommand
    @ApiOperation(value = "根据account获取账号的详细信息")
    @ApiImplicitParam(name = "account", value = "账号", required = true, dataType = "String")
    @RequestMapping(value = "/detailByAccount/{account}", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult> detailByAccount(@PathVariable("account") String account, HttpServletRequest request, HttpServletResponse response) {
        if (!StringUtils.validateParameter(account)) {
            String message = "调用接口【/api/v1/account/detailByAccount/{account}时，参数account不能为空";
            log.warn(message);
            ApiResult apiResult = new ApiResult();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        //ServiceResult<Account> serviceResult = accountService.findByAccount(account);
        //从Redis获取account数据
        String accountDTO = (String) redisManager.get(RedisStorage.ACCOUNT_BY_ACCOUNT_PREFIX + account);
        ApiResult<Account> apiResult = new ApiResult<>();
        apiResult.setSuccess(Boolean.TRUE);
        apiResult.setCode(HttpStatus.OK.value());
        //解析数据
        JSONObject json = (JSONObject) JSONObject.parse(accountDTO);
        if (json != null && !json.isEmpty()) {
            apiResult.setResult(JSONObject.parseObject(json.toJSONString(), Account.class));
        }
        apiResult.setMessage(ServiceResult.SELECT_SUCCESS);
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 返回所有人员，按照字母顺序升序排列
     *
     * @return
     */
    @HystrixCommand
    @ApiOperation(value = "返回所有人员，按照字母顺序升序排列")
    @RequestMapping(value = "/findAllOrderByRealNameAsc", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult> findAllOrderByRealNameAsc() {
        //ServiceResult<List<AccountPojo>> serviceResult = accountService.findAllOrderByRealNameAsc();
        String accountAll = (String) redisManager.get(RedisStorage.ACCOUNT_ALL);
        ApiResult<List<AccountPojo>> apiResult = new ApiResult<>();
        //解析redis数据
        if (StringUtils.isNotEmpty(accountAll)) {
            JSONObject json = (JSONObject) JSONObject.parse(accountAll);
            if (json != null && !json.isEmpty()) {
                JSONArray result = (JSONArray) json.get(Constants.RESULT);
                if (result != null && !result.isEmpty()) {
                    apiResult.setResult(JSONObject.parseArray(result.toJSONString(), AccountPojo.class));
                }
            }
        }
        apiResult.setSuccess(Boolean.TRUE);
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(ServiceResult.SELECT_SUCCESS);
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 模糊查询供应商协同账号信息
     * @return 返回查询结果
     */
    @HystrixCommand
    @ApiOperation(value = "模糊查询供应商协同账号信息")
    @RequestMapping(value = "/blurSearchScAccountInfo", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult> blurSearchScAccountInfo(@RequestBody BlurSearchScAccountVo blurSearchScAccountVo, HttpServletRequest request, HttpServletResponse response) {
        if (!StringUtils.validateParameter(blurSearchScAccountVo.getSearchInfo())) {
            String message = "调用接口【/api/v1/account/blurSearchScAccountInfo时，参数searchInfo不能为空";
            log.warn(message);
            ApiResult<SearchAccountResultPojo> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        // 模糊查询供应商协同账号信息
        ServiceResult<List<SearchAccountDataPojo>> serviceResult = accountService.blurSearchScAccountInfo(blurSearchScAccountVo);

        ApiResult<List<SearchAccountDataPojo>> apiResult = new ApiResult<>();
        apiResult.setSuccess(Boolean.TRUE);
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setResult(serviceResult.getResult());
        apiResult.setMessage(ServiceResult.SELECT_SUCCESS);
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 根据用户的真实姓名，查找用户和用户所在的组。模糊查询
     * @return 返回查询结果
     */
    @HystrixCommand
    @ApiOperation(value = "根据用户的真实姓名，查找用户和用户所在的组。模糊查询")
    @RequestMapping(value = "/searchByRealName", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiImplicitParam(name = "AccountVo", value = "账号的vo类", required = true, dataType = "AccountVo")
    @ResponseBody
    public ResponseEntity<ApiResult> searchByRealName(@RequestBody AccountVo accountVo, HttpServletRequest request, HttpServletResponse response) {
        if (!StringUtils.validateParameter(accountVo.getRealName())) {
            String message = "调用接口【/api/v1/account/searchByRealName时，参数realName不能为空";
            log.warn(message);
            ApiResult<SearchAccountResultPojo> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }
        log.info("前端传递参数为" + accountVo);
        //把用户信息与组信息以及自定义组信息返回
        ServiceResult<SearchAccountResultPojo> serviceResult = new ServiceResult<>();
        //通过当前真实姓名获取用户信息
        ServiceResult<List<SearchAccountDataPojo>> accountListServiceResult = accountService.findByRealNameLike(accountVo);
        log.info("当前真实姓名获取用户信息" + accountListServiceResult);
        SearchAccountResultPojo searchAccountResultPojo = new SearchAccountResultPojo();
        //集合中用户信息
        List<SearchAccountDataPojo> accountList = accountListServiceResult.getResult();
        searchAccountResultPojo.setAccountList(accountList);
        for (int i = 0; i < accountList.size(); i++) {
            //获取到用户信息中的id
            String id = accountList.get(i).getId();
            //通过accountId 去ref_group_account表获取对应的 id
            ServiceResult<List<RefGroupAccount>> refGroupAccountListServiceResult = refGroupAccountService.findByRealId(id);
            //通过accountId 去ref_user_group_account表获取对应的 id
            ServiceResult<List<RefUserGroupAccount>> refUserGroupAccountServiceResult = refUserGroupAccountService.findByRealId(id);
            List<RefGroupAccount> refGroupAccountList = refGroupAccountListServiceResult.getResult();
            List<RefUserGroupAccount> refUserGroupAccountList = refUserGroupAccountServiceResult.getResult();
            List<SearchUserGroupDataPojo> userGroupList = new ArrayList<>();
            for (int j = 0; j < refUserGroupAccountList.size(); j++) {
                //获取到用户信息中的id
                Integer userGroupId = refUserGroupAccountList.get(j).getUserGroupId();
                //通过id获取自定义组信息
                ServiceResult<UserGroup> userGroupData = userGroupService.findByRealId(userGroupId);
                UserGroup result = userGroupData.getResult();
                if (result != null) {
                    SearchUserGroupDataPojo searchUserGroupDataPojo = new SearchUserGroupDataPojo();
                    BeanUtils.copyProperties(result, searchUserGroupDataPojo);
                    userGroupList.add(searchUserGroupDataPojo);
                }
            }
            searchAccountResultPojo.setUserGroupList(userGroupList);
            List<SearchGroupDataPojo> groupList = new ArrayList<>();
            for (int j = 0; j < refGroupAccountList.size(); j++) {
                //获取到用户信息中的id
                String groupId = refGroupAccountList.get(j).getGroupId();
                //通过id 获取到组信息
                ServiceResult<Group> groupData = groupService.findByRealId(groupId);
                Group result = groupData.getResult();
                if (result != null) {
                    SearchGroupDataPojo searchGroupDataPojo = new SearchGroupDataPojo();
                    BeanUtils.copyProperties(result, searchGroupDataPojo);
                    groupList.add(searchGroupDataPojo);
                }
            }
            searchAccountResultPojo.setGroupList(groupList);
        }
        serviceResult.setResult(searchAccountResultPojo);
        ApiResult<SearchAccountResultPojo> apiResult = new ApiResult<SearchAccountResultPojo>();
        apiResult.setSuccess(Boolean.TRUE);
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setResult(serviceResult.getResult());
        apiResult.setMessage(ServiceResult.SELECT_SUCCESS);
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 这个接口不再用了
     * 获取近期的联系人。按置顶顺序降序排列，按最后聊天时间降序排列。显示未读消息数量
     *
     * @return
     */
//    @HystrixCommand
//    @ApiOperation(value = "获取近期的联系人。按置顶顺序降序排列，按最后聊天时间降序排列。显示未读消息数量")
//    @ApiImplicitParam(name = "account", value = "账号", required = true, dataType = "String")
//    @RequestMapping(value = "/current/{account}", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
//    @ResponseBody
//    public ResponseEntity<ApiResult> current(@PathVariable("account") String account, HttpServletRequest request, HttpServletResponse response) {
//        if (!StringUtils.validateParameter(account)) {
//            String message = "调用接口【/api/v1/account/current/{account}时，参数account不能为空";
//            log.warn(message);
//            ApiResult<List<AccountPojo>> apiResult = new ApiResult<>();
//            apiResult.setSuccess(Boolean.FALSE);
//            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
//            apiResult.setMessage(message);
//            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
//        }
//
//        ServiceResult<List<AccountPojo>> serviceResult = accountService.findLastContact(account);
//
//        ApiResult<List<AccountPojo>> apiResult = new ApiResult<>();
//        apiResult.setSuccess(Boolean.TRUE);
//        apiResult.setCode(HttpStatus.OK.value());
//        apiResult.setResult(serviceResult.getResult());
//        apiResult.setMessage(ServiceResult.SELECT_SUCCESS);
//        return new ResponseEntity<>(apiResult, HttpStatus.OK);
//    }

    /**
     * 登录。修改erp9_login、last_erp9_login_time、xl_login、last_lx_login_time字段
     *
     * @return 返回登录结果
     */
    @HystrixCommand
    @ApiOperation(value = "登录。修改erp9_login、last_erp9_login_time、xl_login、last_lx_login_time字段")
    @ApiImplicitParam(name = "account", value = "账号", required = true, dataType = "String")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "account", value = "账号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "entrance", value = "登录入口。1表示erp9登录，2表示芯聊客户端登录", required = true, dataType = "Integer")
    })
    @RequestMapping(value = "/login/{account}/{entrance}", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult> login(@PathVariable("account") String account,
                                           @PathVariable("entrance") Integer entrance,
                                           HttpServletRequest request, HttpServletResponse response) {
        if (!StringUtils.validateParameter(account) || null == entrance) {
            String message = "调用接口【/api/v1/account/login/{account}/{entrance}时，参数account和entrance不能为空";
            log.warn(message);
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }
        // 根据账号记录登录状态
        ServiceResult<Boolean> serviceResult = accountService.login(account, entrance);

        // 给最近联系人发送mq消息、更新最近联系人数据
        sendMqMsgToLastContact(account);

        ApiResult<Boolean> apiResult = new ApiResult<>();
        apiResult.setSuccess(serviceResult.getSuccess());
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(serviceResult.getMessage());
        apiResult.setResult(serviceResult.getResult());
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 退出。修改erp9_login、xl_login字段
     *
     * @return 返回退出结果
     */
    @HystrixCommand
    @ApiOperation(value = "退出。修改erp9_login、xl_login字段")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "account", value = "账号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "entrance", value = "登录入口。1表示erp9登录，2表示芯聊客户端登录", required = true, dataType = "Integer")
    })
    @RequestMapping(value = "/logout/{account}/{entrance}", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult> logout(@PathVariable("account") String account,
                                            @PathVariable("entrance") Integer entrance,
                                            HttpServletRequest request, HttpServletResponse response) {
        if (!StringUtils.validateParameter(account) || null == entrance) {
            String message = "调用接口【/api/v1/account/logout/{entrance}时，参数account和entrance不能为空";
            log.warn(message);
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        // 根据账号记录退出状态
        ServiceResult<Boolean> serviceResult = accountService.logout(account, entrance);

        // 给最近联系人发送mq消息、更新最近联系人数据
        sendMqMsgToLastContact(account);

        ApiResult<Boolean> apiResult = new ApiResult<>();
        apiResult.setSuccess(serviceResult.getSuccess());
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(serviceResult.getMessage());
        apiResult.setResult(serviceResult.getResult());
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 给最近联系人发送mq消息、更新最近联系人数据
     */
    private void sendMqMsgToLastContact(String username) {
        List<String> lastContactList = chatPairService.selectLastContactAccounts(username).getResult();
        SendRabbitMqMessageThread sendRabbitMqMessageThread = new SendRabbitMqMessageThread(lastContactList, rabbitMqParamConfig.getExchange().get(RabbitMqExchangeMap.CURRENT_EXCHANGE));
        threadPoolManager.execute(sendRabbitMqMessageThread);
    }
}